﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Event/CapEventBus 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       CapEventBus
* 创建时间：  2025/6/4 8:55:02
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using DotNetCore.CAP;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using SSPivot.Event.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediatR;

namespace SSPivot.Event
{
    public class EventBus : IEventPublisher
    {
        private readonly IMediator _mediator;
        private readonly ICapPublisher _capPublisher;
        private readonly IServiceProvider _serviceProvider;

        public EventBus(IMediator mediator, ICapPublisher capPublisher, IServiceProvider serviceProvider)
        {
            _mediator = mediator;
            _capPublisher = capPublisher;
            _serviceProvider = serviceProvider;
        }

        public async Task PublishLocalAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
            where TEvent : INotification
        {
            await _mediator.Publish(@event, cancellationToken);
        }

        public async Task PublishDistributedAsync<TEvent>(TEvent @event, IDictionary<string, string> headers = null,
            CancellationToken cancellationToken = default)
            where TEvent : class
        {
            using var scope = _serviceProvider.CreateScope();
            var capPublisher = scope.ServiceProvider.GetRequiredService<ICapPublisher>();

            await capPublisher.PublishAsync(typeof(TEvent).FullName, @event, headers, cancellationToken);
        }
    }
}
